<template>
  <div
    class="ripple-button"
    :class="`el-button--${type}`"
    ref="button"
    @mouseenter="handleMouseEnter"
    @mouseleave="handleMouseLeave"
    @click="$emit('click')"
  >
    <i
      v-if="loading"
      class="el-icon-loading"
    />
    <i
      v-else-if="icon"
      class="icon"
      :class="icon"
    />
    <span
      class="ripple"
      ref="ripple"
    >
    </span>
    <span
      v-if="loading||icon"
      class="space"
    ></span>
    <slot />
  </div>
</template>

<script>
export default {
  name: 'RippleButton',
  props: {
    type: {
      type: String,
      default: 'default'
    },
    icon: {
      type: String
    },
    loading: {
      type: Boolean,
      default: false
    }
  },
  methods: {
    handleMouseEnter (event) {
      this.$refs.ripple.classList.add('animation')
      this.$refs.ripple.style.width = this.$refs.button.offsetWidth + 'px'
      this.$refs.ripple.style.height = this.$refs.button.offsetWidth + 'px'
      this.$refs.ripple.style.top =
        -(this.$refs.button.offsetHeight - event.offsetY) + 'px'
      this.$refs.ripple.style.left =
        -(this.$refs.button.offsetWidth / 2 - event.offsetX) + 'px'
    },
    handleMouseLeave () {
      this.$refs.ripple.classList.remove('animation')
    }
  }
}
</script>

<style lang="scss" scoped>
.ripple-button + .ripple-button {
  margin-left: 10px;
}
.el-button--default {
  color: #606266;
  background: #fff;
  border: 1px solid #dcdfe6;
}
.ripple-button {
  position: relative;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 12px 20px;
  font-size: 14px;
  line-height: 1;
  box-sizing: border-box;
  border-radius: 4px;
  &:hover {
    cursor: pointer;
  }
  .space {
    display: inline-block;
    width: 4px;
    height: 1px;
  }
}

.ripple {
  display: block;
  position: absolute;
  border-radius: 100%;
  background: rgba(255, 255, 255, 0.5);
  transform: scale(0);
}

.animation {
  animation: ripple 0.4s ease-in;
  animation-fill-mode: forwards;
}

@keyframes ripple {
  0% {
    transform: scale(0);
  }
  100% {
    transform: scale(3);
  }
}
</style>
